package com.securitytrace.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import com.securitytrace.client.ManagerClient;
import com.securitytrace.dataModel.AddressComBoxModel;
import com.securitytrace.dataModel.RoleComBoxModel;
import com.securitytrace.dataModel.UserDataModel;
import com.securitytrace.init.Init;
import com.securitytrace.model.Address;
import com.securitytrace.model.Role;
import com.securitytrace.model.User;
import com.securitytrace.popupwindow.UserWindow;

public class AddUserButtonListener implements ActionListener{

	private UserWindow userWindow;
	
	public AddUserButtonListener(UserWindow userWindow) {
		this.userWindow = userWindow;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String account = userWindow.getUserAccountTextField().getText();
		String password = userWindow.getUserPasswordTextField().getText();
		if(account.trim().isEmpty()) {
			JOptionPane.showMessageDialog(userWindow, "帐号不能为空");
		}else if(password.trim().isEmpty()) {
			JOptionPane.showMessageDialog(userWindow, "密码不能为空");
		}else {
			User user = new User();
			user.setAccount(account);
			user.setPassword(password);
			
			String roleName = (String) userWindow.getUserRoleComboBox().getSelectedItem();
			Long roleId = RoleComBoxModel.getRoleMap().get(roleName);
			Role role = new Role();
			role.setId(roleId);
			role.setName(roleName);
			
			String addressName = (String) userWindow.getUserAddressComboBox().getSelectedItem();
			long addressId = AddressComBoxModel.getAddressMap().get(addressName);
			Address address = new Address();
			address.setId(addressId);
			address.setAddressName(addressName);
			user.setRole(role);
			user.setAddress(address);
			
			addUserToDatabase(user, roleId, addressId);
			userWindow.dispose();
		}
	}
	
	private void addUserToDatabase(User user, long roleId, long addressId) {
		try {
			Init.getUserService().create(user, roleId, addressId);
			ManagerClient managerClient = userWindow.getManagerClient();
			UserDataModel userDataModel = managerClient.getUserModel();
			
			int currentPage = userDataModel.getUserCurrentPage();
			int pageSize = managerClient.getPageSize();
			int totalPage = 1;
			
			List<User> users = new ArrayList<User>();
			users = Init.getUserService().getListByPage((currentPage - 1)  * pageSize, pageSize);
			
			long userNumber = Init.getUserService().getTotalCount();
			if((userNumber % pageSize) == 0) {
				totalPage = (int) (userNumber / pageSize);
			}else {
				totalPage = (int) (userNumber / pageSize) + 1;
			}
			userDataModel.setUserTotal(totalPage);
			userDataModel.setDataVector(users);
			managerClient.getUserPanel().getPageInfoLabel().setText(userDataModel.getUserPageInfo());
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null,"操作失败");
		}
	}
}
